package com.zy.swagger.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zy.swagger.annotation.LogCostTime;
import com.zy.swagger.base.BaseDao;
import com.zy.swagger.base.BaseServiceImpl;
import com.zy.swagger.constant.ProjectConstant;
import com.zy.swagger.converter.AppManageConverter;
import com.zy.swagger.dao.AppManageDao;
import com.zy.swagger.dao.SysUserDao;
import com.zy.swagger.dto.AppManageDTO;
import com.zy.swagger.dto.CommonIdDTO;
import com.zy.swagger.entity.AppManage;
import com.zy.swagger.service.AppManageService;
import com.zy.swagger.util.PageHelperTool;
import com.zy.swagger.vo.AppManageVO;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 应用管理表(表t_app_manage)服务接口实现类
 *
 * @author ZY
 * @date 2021-04-23 22:37:19
 */
//@DubboService(interfaceClass = AppManageService.class)
@Service("appManageService")
public class AppManageServiceImpl extends BaseServiceImpl<AppManage, Integer, Object> implements AppManageService {

    /**
     * 注入持久层对象
     */
    @Resource
    private AppManageDao dao;

    @Resource
    private SysUserDao sysUserDao;

    /**
     * 定义抽象方法getDao获取当前实体Mapper对象
     *
     * @return 当前实体Mapper对象
     */
    @Override
    protected BaseDao<AppManage> getDao() {
        return this.dao;
    }

    /**
     * 新增数据
     *
     * @param dto 参数对象
     * @return 视图对象
     */
    @Override
    public AppManageVO insert(AppManageDTO dto) throws Exception {
        AppManage entity = AppManageConverter.convertFromDTO(dto);
        if (!StringUtils.isEmpty(dto.getSwaggerUrl())) {
            Map<String, String> envMap = Maps.newHashMap();
            envMap.put(dto.getEnv(), dto.getSwaggerUrl());
            entity.setSwaggerUrl(JSON.toJSONString(envMap));
        }
        entity.setCreateTime(new Date());
        AppManage res = super.insertSelective(entity);
        if (res != null) {
            return AppManageConverter.convertToVO(res);
        }
        return null;
    }

    /**
     * 删除对象
     *
     * @param dto 参数对象
     * @return true:删除成功 false:删除失败
     */
    @Override
    public Integer delete(CommonIdDTO dto) {
        return super.deleteByPrimaryKey(Integer.parseInt(dto.getId()));
    }

    /**
     * 更新对象
     *
     * @param dto 待更新的DTO对象
     * @return 成功返回更新后的VO对象，失败返回null
     */
    @Override
    public AppManageVO update(AppManageDTO dto) {
        AppManage entity = AppManageConverter.convertFromDTO(dto);
        AppManage existApp = super.getByPrimaryKey(dto.getId());
        if (!StringUtils.isEmpty(dto.getSwaggerUrl())) {
            String swaggerUrl = existApp.getSwaggerUrl();
            Map<String, String> envMap;
            if (StringUtils.isEmpty(swaggerUrl)) {
                envMap = Maps.newHashMap();
            } else {
                envMap = JSON.parseObject(swaggerUrl, Map.class);
            }
            envMap.put(dto.getEnv(), dto.getSwaggerUrl());
            entity.setSwaggerUrl(JSON.toJSONString(envMap));
        }
        entity.setUpdateTime(new Date());
        int res = super.updateByPrimaryKeySelective(entity);
        if (res == 1) {
            return AppManageConverter.convertToVO(entity);
        }
        return null;
    }

    /**
     * 根据ID查询数据
     *
     * @param dto 主键DTO对象
     * @return 成功返回对应ID的VO对象，失败返回null
     */
    @LogCostTime
    @Override
    public AppManageVO getById(CommonIdDTO dto) {
        AppManage entity = super.getByPrimaryKey(Integer.parseInt(dto.getId()));
        if (entity != null) {
            return AppManageConverter.convertToVO(entity);
        }
        return null;
    }

    /**
     * 根据条件查询数据集合
     *
     * @param dto 查询条件对象
     * @return 满足条件的数据集合
     */
    @Override
    public List<AppManageVO> getList(AppManageDTO dto) {
        Example example = new Example(AppManage.class);
        Example.Criteria criteria = example.createCriteria();
        if (dto.getBelongEnd() != null) {
            criteria.andEqualTo("belongEnd", dto.getBelongEnd());
        }

        List<AppManage> list = super.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            List<AppManageVO> retList = new ArrayList<>();
            this.convertList(dto, list, retList);
            return retList;
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询分页
     *
     * @param dto  查询条件
     * @return 满足条件的分页
     */
    @Override
    public PageInfo<AppManageVO> getPageInfo(AppManageDTO dto) {
        Integer pageNum = dto.getPageNum();
        Integer pageSize = dto.getPageSize();

        Example example = new Example(AppManage.class);
        Example.Criteria criteria = example.createCriteria();
        if (dto.getBelongEnd() != null) {
            criteria.andEqualTo("belongEnd", dto.getBelongEnd());
        }
        if (dto.getUserId() != null) {
            criteria.andEqualTo("userId", dto.getUserId());
        }
        if (!StringUtils.isEmpty(dto.getAppName())) {
            criteria.orLike("appName", "%" + dto.getAppName() + "%");
            criteria.orLike("appDesc", "%" + dto.getAppName() + "%");
            criteria.orLike("port", "%" + dto.getAppName() + "%");
        }

        PageInfo<AppManage> pageInfo = PageHelper.startPage(pageNum, pageSize).setOrderBy("id desc").doSelectPageInfo(() -> super.selectByExample(example));
        if (pageInfo == null || CollectionUtils.isEmpty(pageInfo.getList())) {
            return PageHelperTool.initPageInfoObj(pageNum, 0, pageSize, new PageInfo<>(Lists.newArrayList()));
        }

        List<AppManageVO> retList = new ArrayList<>();
        this.convertList(dto, pageInfo.getList(), retList);
        return PageHelperTool.initPageInfoObj(pageNum, (int) pageInfo.getTotal(), pageSize, new PageInfo<>(retList));
    }


    /**
     * 转换返回的list
     *
     * @param dto 入参
     * @param list 查询到的list
     * @param retList 要返回的list
     */
    private void convertList(AppManageDTO dto, List<AppManage> list, List<AppManageVO> retList) {
        list.forEach(x -> {
            AppManageVO vo = AppManageConverter.convertToVO(x);
            vo.setUserName(sysUserDao.selectByPrimaryKey(x.getUserId()).getName());
            vo.setBelongEndName(AppManageConverter.convertBelongEnd(x.getBelongEnd()));
            if (StringUtils.isEmpty(vo.getSwaggerUrl())) {
                String swaggerUrl = "http://" + ProjectConstant.getEnvMap().get(dto.getEnv()) + ":" + vo.getPort() + "/doc.html";
                vo.setSwaggerUrl(swaggerUrl);
            } else {
                Map<String, String> map = JSON.parseObject(vo.getSwaggerUrl(), Map.class);
                if (map.containsKey(dto.getEnv())) {
                    vo.setSwaggerUrl(map.get(dto.getEnv()));
                } else {
                    String swaggerUrl = "http://" + ProjectConstant.getEnvMap().get(dto.getEnv()) + ":" + vo.getPort() + "/doc.html";
                    vo.setSwaggerUrl(swaggerUrl);
                }
            }
            retList.add(vo);
        });
    }
}